<?php


declare(strict_types=1);

/**
 * testController.php
 * 微信用户管理后台
 * User：Abell
 * Date：2020/4/15
 * Time：18:11
 */

namespace App\Controller\Abell;

use App\Controller\AbstractController;
use App\Nats\Publish\ProxyNats;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Utils\ApiUtils;
use Hyperf\Di\Annotation\Inject;//引入@Inject注解
use Hyperf\Utils\Context;
use App\Utils\UploadUtil;
use App\Model\Wxvisit as WxvisitModel;
use App\Model\Wxuser as WxuserModel;
use App\Server\CurlApi;
use Hyperf\Utils\Parallel;
use App\Model\Area as AreaModel;

/**
 * @Controller()
 */
class  TestController extends AbstractController
{
    /**
     * @Inject()
     * @var \Hyperf\Contract\SessionInterface
     */
    private $session;

    /**
     * 测试
     * @RequestMapping(path="/abell/test/helo", methods="get,post")
     */
    public function helo(){
//        $get_path = config('server.settings.document_root');
//        return $get_path;
        $img_path = config('web.img_path');
        $img_path_list = explode('/',$img_path);
        var_dump($img_path_list);
        // 去掉前两个元素
        
    }

    /**
     * 测试
     * @RequestMapping(path="/abell/test/test", methods="get,post")
     */
    public function test()
    {
        $aepara = new Parallel();
        $start_time = date( "Y-m-d H:i",time());
        $aepara->add(function () {
            for ($i = 0; $i < 5000; $i++) {
//            $this->visitdata();
            $this->testdata();
        }
        });
        $aepara->add(function (){
            for ($i = 0; $i < 5000; $i++) {
                //            $this->visitdata();
                $this->testdata();

            }
        });
        $aepara->add(function (){
            for ($i = 0; $i < 5000; $i++) {
                //            $this->visitdata();
                $this->testdata();
            }
        });
        $aepara->add(function (){
            for ($i = 0; $i < 5000; $i++) {
                //            $this->visitdata();
                $this->testdata();
            }
        });
        $aepara->add(function (){
            for ($i = 0; $i < 5000; $i++) {
                //            $this->visitdata();
                $this->testdata();
            }
        });
        var_dump('运行结束,开始时间');
        var_dump($start_time);
        var_dump('结束时间');
        var_dump(date( "Y-m-d H:i",time()));
        $result = $aepara->wait();
        return $result;

    }

    public function handleDescriptionHtml($description)
    {
        // 批量对微信呢称进行base64位
//        $chagename = WxuserModel::query()->get()->toArray();
//        foreach ($chagename as $cname) {
////            var_dump($cname['nickname']);
//            $base64name = base64_encode($cname['nickname']);
//            var_dump($base64name);
//        }
//        return $this->response->json(ApiUtils::send(0,'ok',$chagename));

        // 富文本内容正则匹配处理图片资源
//        $content = WxnoticeModel::query()->where('id',2)->value('content');
//        // 匹配处理外部链接
//        $result = $this->handleDescriptionHtml($content);
//
//        return $this->response->json(ApiUtils::send(0,'ok',$result,1));
        // 随机生成微信用户 和 访问记录
        // 匹配返回富文本里面的图片链接
        $content_decode = htmlspecialchars_decode($description); ///把一些预定义的 HTML 实体转换为字符
        $content_empty = str_replace('&nbsp;','',$content_decode);
        $img_str_list = explode('<img src="',$content_empty);
        array_shift($img_str_list);
        $image_array = [];
        foreach ($img_str_list as $img_str) {
            $img_urls = explode('"',$img_str);
            array_push($image_array,$img_urls[0]);
        }
        // 下载富文本里面的图片链接到本地
        foreach ($image_array as $img_url) {
            $download_img = UploadUtil::download_img($img_url);
            var_dump($download_img);
            if($download_img['code']){
                var_dump('图片下载失败');
            }else{
                // 替换富文本的内容
                $content_empty = str_replace($img_url,$download_img['data']['imgpath'],$content_empty);
            }
        }
        return $content_empty;
    }

    /**
     * 测试
     * @RequestMapping(path="/abell/test/download_img", methods="get,post")
     */
    public function downloadImg(RequestInterface $request){
        $url = $request->input('url','https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1654304818,1911023771&fm=26&gp=0.jpg');
        $download_img = UploadUtil::download_img($url);
        return $this->response->json(ApiUtils::send($download_img['code'],'ok',$download_img,1));
    }

    public function downloadImg1($url=''){
        $url = 'https://images.pexels.com/photos/3879062/pexels-photo-3879062.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500';
        $url = 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1654304818,1911023771&fm=26&gp=0.jpg';
        var_dump($url);
        $ch = curl_init();
        $fp=fopen('./girl.jpg', 'w');
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 100);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        $error = curl_error($ch);
        fclose($fp);

        $size = filesize("./girl.jpg");
        if ($size != $info['size_download']) {
            echo "下载失败";
            echo $error;
        } else {
            echo "下载成功";
        }
        curl_close($ch);
    }

    /**
     * nat功能使用
     * Abell 2020/4/18
     * @RequestMapping(path="/abell/test/aenats", methods="get,post")
     */
    public function aenats(RequestInterface $request)
    {
        // nats数据获取
        $obj = $this->container->get(ProxyNats::class);
        $msg = $obj->sync(json_encode(['openid'=>'adfadsfasd','type'=>1]),'sg_phonecode.recharge');
        $msg_json = json_decode($msg,true);
        $msg_array = $msg_json['data'];
        // 文件夹创建和赋权
        $file_path = substr('/upload_file/image_upload_file/img/20200427/',1);
        var_dump($file_path);
        if(! is_dir($file_path)){
            $create_file = mkdir($file_path,0777,true);
            if($create_file)  chmod($file_path,0665);
        }
        return $file_path;
    }

    /**
     * session的使用,存入session
     * @RequestMapping(path="/abell/test/save_session", methods="get,post")
     */
    public function saveSession(RequestInterface $request)
    {
        $data = $request->input('id');
        $this->session->set('id', $data);
    }
    // 如果报错的话需要执行   composer require hyperf/session  && php bin/hyperf.php vendor:publish hyperf/session
    // 以及在config/autoload/middleware.php 添加代码 \Hyperf\Session\Middleware\SessionMiddleware::class,

    /**
     * session的使用,存入session
     * @RequestMapping(path="/abell/test/check", methods="get,post")
     */

    public function check(RequestInterface $request)
    {
        return $this->session->get('id');
    }

    /**
     * 批量创建测试visit数据
     * @RequestMapping(path="/abell/test/visitdata", methods="get,post")
     *
     */
    public function visitdata($start_time=1585734237)
    {
        //随机获取一个用户
        $type_explain_array = ['/home/index', '/home/hello', '/home/hello1', '/home/hello2', '/home/hello3', '/home/hello6', 'login2reg'];
        $type_randkey = array_rand($type_explain_array);
        $rand_user = WxuserModel::inRandomOrder()->first();
        $start_time = rand($start_time, time());
        $data = [
            'openid' => $rand_user['openid'],
            'type_explain' => $type_explain_array[$type_randkey],
            'add_time' => $start_time,
            'update_time' => $start_time
        ];
        var_dump($data);
        $add_visit = WxvisitModel::query()->insertGetId($data);
//        return $this->response->json(ApiUtils::send(0, 'ok', $add_visit), 1);
    }

    /**
     * 模拟小程序访问数据
     * 每次用户访问会生成两条记录,一条是实时的访问pv,另一条是当天的uv 当天的uv记录生成后当天不会再增加,而是只做修改更新时间
     * p_id = 0 是pv记录  p_id = 1 是uv记录  p_id=3 是当天页面的总访问量
     * Abell 2020/4/17
     * @RequestMapping(path="/abell/test/visit", methods="get,post")
     */
    public function visit(RequestInterface $request)
    {

        if ($request->has('openid')) {
            $openid = WxuserModel::where(['openid' => $request->input('openid')])->value('id');
        } else {
            return $this->response->json(ApiUtils::send(400, 'Error', '没有传入用户参数'));
        }
        $update_time['add_time'] = time();
        // strtotime(date('Y-m-d',time()));
        $map = [
            'openid' => $openid, 'p_id' => 1
        ];
        // 判断该用户是否已经存在 p_id=1 记录,不存在就创建
        $has_user = WxvisitModel::where(['openid' => $openid, 'p_id' => 1])->get();
        if ($has_user) {
            //            // 更新 p_id=1 访问时间
            var_dump('更新 p_id=1 访问时间');
            $update_time['add_time'] = time();
            WxvisitModel::where(['openid' => $openid, 'p_id' => 1])->update($update_time);
        } else {

            var_dump('新增uv记录');
        }
        return 'hello';
    }

    /**
     * 批量创建测试数据
     * @RequestMapping(path="/abell/test/testdata", methods="get,post")
     */
    public function testdata()
    {
        // 随机邀请人
        $random_city = $this->randCity();
        if(mt_rand(0,5) == 1){
            $get_openid = WxuserModel::query()->inRandomOrder()->first();
            $newUser = Db::table('wxuser')->insertGetId([
                'openid' => $this->open_id(),
                'nickname' => base64_encode($this->randName()),
                'avatarurl' => 'https://avatar.csdnimg.cn/2/1/A/3_gjalj10.jpg',
                'gender' => rand(0, 1),
                'country' => '中国',
                'province' => $random_city['province_short_name'],
                'pid' => $get_openid['openid'],
                'city' => $random_city['city_short_name'],
                'language' => 'CH-ch',
                'mobile' => $this->randPhone(),
                'haspay' => rand(0, 1),
                'hasadd' => rand(0, 1),
                'add_time' => time(),
                'update_time' => time()
            ]);
            var_dump($newUser);
            return true;
        }else{
            $newUser = Db::table('wxuser')->insertGetId([
                'openid' => $this->open_id(),
                'nickname' => base64_encode($this->randName()),
                'avatarurl' => 'https://avatar.csdnimg.cn/2/1/A/3_gjalj10.jpg',
                'gender' => rand(0, 1),
                'country' => '中国',
                'province' => $random_city['province_short_name'],
                'city' => $random_city['city_short_name'],
                'language' => 'CH-ch',
                'mobile' => $this->randPhone(),
                'haspay' => rand(0, 1),
                'hasadd' => rand(0, 1),
                'add_time' => $this->randTime(),
                'update_time' => $this->randTime(),
            ]);
            var_dump($newUser);
            return true;
        }
    }

    /**
     * 随机电话号码
     * @RequestMapping(path="/abell/test/rand_phone", methods="get,post")
     */
    public function randPhone(){
        $head = ['133','149','153','173','177','180','181','189','199','130','131','132','145','155','156','166','171','175','176','185','186','166','134','135','136',
            '137','138','139','147','150','151','152','157','158','159','172','178','182','183','184','187','188','198','192','170'];
        $head_num = array_rand($head);
        $code_array_num = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        $random_phone = array();
        for ($i = 0; $i < 8; $i++) {
            $key = array_rand($code_array_num, 1);
            array_push($random_phone, $code_array_num[$key]);
        }
        // 数组转字符串
        $verification_phone = implode('', $random_phone);
        return $head[$head_num].$verification_phone;
    }

    /**
     * 时间随机值 2019-05-01 09:10:30 默认开始时
     * @RequestMapping(path="/abell/test/rand_time", methods="get,post")
     */
    public function randTime($start=1556673030,$end=0){
        $end = $end ? $end : time();
        $time = rand($start,$end);
        return $time;
    }

    /**
     * 批量创建测试数据
     * @RequestMapping(path="/abell/test/rand_city", methods="get,post")
     */
    public function randCity(){
        $result = AreaModel::query()->inRandomOrder()->first();
        return $result;
    }

    /**
     * 批量创建测试数据
     * @RequestMapping(path="/abell/test/open_id", methods="get,post")
     */
    public function open_id($head = "ogtzs4", $length = 21, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
    {
        if (!is_int($length) || $length < 0) {
            return '$length 必须为Int类型';
        }
        $string = '';
        for ($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $head . $string;
    }

    // wxuser 旧版本代码备份

    /**
     * 小程序分享查询上级接口
     * Abell
     * 2020/4/21
     * @RequestMapping(path="/abell/wxuser/shares", methods="get")
     */
    public function shares(RequestInterface $request)
    {
        // 查询分享上级
        if ($request->has('openid')) {
            $has_user = WxuserModel::query()->where(['openid' => $request->input('openid')])->get();
            if ($has_user) {
                return $this->response->json(ApiUtils::send(0, 'ok', $has_user, 1));
            } else {
                return $this->response->json(ApiUtils::send(400, 'Error', '用户不存在', 1));
            }
        } else {
            return $this->response->json(ApiUtils::send(500, 'Error', '禁止访问', 1));
        }
    }

    /**
     * 小程序签到接口
     * Abell
     * 2020/4/21
     * @RequestMapping(path="/abell/wxuser/sign2", methods="get")
     */
    public function sign2(RequestInterface $request)
    {
        if ($request->has('openid')) {
            // 判断用户是否存在 , 当天是否已经签到过
            $has_user = WxuserModel::query()->where(['openid' => $request->input('openid')])->exists();
            if ($has_user) {
                $has_sign = Lottery::addSign($request->input('openid'));
                return $this->response->json(ApiUtils::send($has_sign['code'], $has_sign['msg'], $has_sign['data'], 1));
            } else {
                return $this->response->json(ApiUtils::send(400, 'Error', '用户不存在', 1));
            }

        } else {
            return $this->response->json(ApiUtils::send(500, 'Error', '禁止访问', 1));
        }
    }
    // wxserver
    /**
     * 在线客服查询回复,通过token解析user_id
     * Abell
     * 2020/4/20
     * @RequestMapping(path="/abell/wxservice/reply", methods="get,post")
     */
    public function reply(RequestInterface $request){
        //jwt解析用户id 接收并解析传过来的token
        $jwt = Context::get('jwt_token');
        $data['user_id'] = $jwt['uid'];
        $data['openid'] = $jwt['account'];
        var_dump($jwt);
        var_dump($data);

    }

    /**
     * 小程序用户提交在线客服表格请求 旧接口,直接请求
     * Abell
     * 2020/4/18
     * @RequestMapping(path="/abell/wxservice/formmsgold", methods="get,post")
     */
    public function formmsgold(RequestInterface $request){
        if($request->has('openid')){
            $has_user = WxuserModel::where(['openid'=>$request->input('openid')])->value('id');
            if($has_user){
                // 准备提交用户的在线表格
                $form_req = WxserviceModel::insertGetId([
                    'add_time'  => time(),
                    'user_id'   => $has_user,
                    'title'     => $request->input('title'),
                    'openid'    => $request->input('openid'),
                    'mobile'    => $request->input('mobile'),
                    'detail'    => $request->input('detail'),
                    'statue'    => 0
                ]);
                if($form_req){
                    return $this->response->json(ApiUtils::send(0,'ok',$form_req,1));
                }else{
                    return $this->response->json(ApiUtils::send(400,'Error','提交失败,请稍后再试',1));
                }
            }else{
                return $this->response->json(ApiUtils::send(400,'Error','用户openid不存在',1));
            }
        }else{
            return $this->response->json(ApiUtils::send(400,'Error','没有传入用户参数',1));
        }
    }

    /// wx/wxlogin
    public function miniLoginold($data){
        $appid = config('web.wx_account.appid');
        $grant_type = "authorization_code"; //授权（必填）
        // 新用户注册
        $encryptedData = $data['encryptedData'];
        $iv = $data['iv'];
        $signature = $data['signature'];
        $rawData = $data['rawData'];
//        $rawData = htmlspecialchars_decode($data['rawData']);
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".config('web.wx_account.appsecret')."&js_code=".$data['code']."&grant_type=".$grant_type;
        $curl = new CurlApi();
        $res = json_decode($curl->get($url));
        $sessionKey = $res['session_key']; //取出json里对应的值
        $signature2 = sha1(htmlspecialchars_decode($rawData).$sessionKey);
        // 验证签名
        if($signature2 !== $signature){
            return false; //验证签名失败
        }
        // 获取解密后的数据
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if($errCode == 0){
            return $data;
        }else{
            return false;//登录失败
        }
    }
    /**
     * 随机生成姓名
     * @RequestMapping(path="/abell/test/rand_name", methods="get,post")
     */
    public function randName()
    {
        $first_name = array('赵','钱','孙','李','周','吴','郑','王','冯','陈','褚','卫','蒋','沈','韩','杨',
            '朱','秦','尤','许','何','吕','施','张','孔','曹','严','华','金','魏','陶','姜','戚','谢','邹','喻',
            '柏','水','窦','章','云','苏','潘','葛','奚','范','彭','郎','鲁','韦','昌','马','苗','凤','花','方',
            '任','袁','柳','鲍','史','唐','费','薛','雷','贺','倪','汤','滕','殷','罗','毕','郝','安','常','傅',
            '卞','齐','元','顾','孟','平','黄','穆','萧','尹','姚','邵','湛','汪','祁','毛','狄','米','伏','成',
            '戴','谈','宋','茅','庞','熊','纪','舒','屈','项','祝','董','梁','杜','阮','蓝','闵','季','贾','路',
            '娄','江','童','颜','郭','梅','盛','林','钟','徐','邱','骆','高','夏','蔡','田','樊','胡','凌','霍',
            '虞','万','支','柯','管','卢','莫','柯','房','裘','缪','解','应','宗','丁','宣','邓','单','杭','洪',
            '包','诸','左','石','崔','吉','龚','程','嵇','邢','裴','陆','荣','翁','荀','于','惠','甄','曲','封',
            '储','仲','伊','宁','仇','甘','武','符','刘','景','詹','龙','叶','幸','司','黎','溥','印','怀','蒲',
            '邰','从','索','赖','卓','屠','池','乔','胥','闻','莘','党','翟','谭','贡','劳','逄','姬','申','扶',
            '堵','冉','宰','雍','桑','寿','通','燕','浦','尚','农','温','别','庄','晏','柴','瞿','阎','连','习',
            '容','向','古','易','廖','庾','终','步','都','耿','满','弘','匡','国','文','寇','广','禄','阙','东',
            '欧','利','师','巩','聂','关','荆','司马','上官','欧阳','夏侯','诸葛','闻人','东方','赫连','皇甫',
            '尉迟','公羊','澹台','公冶','宗政','濮阳','淳于','单于','太叔','申屠','公孙','仲孙','轩辕','令狐',
            '徐离','宇文','长孙','慕容','司徒','司空');
        $last_name = array('伟','刚','勇','毅','俊','峰','强','军','平','保','东','文','辉','力','明','永',
            '健','世','广','志','义','兴','良','海','山','仁','波','宁','贵','福','生','龙','元','全','国','胜',
            '学','祥','才','发','武','新','利','清','飞','彬','富','顺','信','子','杰','涛','昌','成','康','星',
            '光','天','达','安','岩','中','茂','进','林','有','坚','和','彪','博','诚','先','敬','震','振','壮',
            '会','思','群','豪','心','邦','承','乐','绍','功','松','善','厚','庆','磊','民','友','裕','河','哲',
            '江','超','浩','亮','政','谦','亨','奇','固','之','轮','翰','朗','伯','宏','言','若','鸣','朋','斌',
            '梁','栋','维','启','克','伦','翔','旭','鹏','泽','晨','辰','士','以','建','家','致','树','炎','德',
            '行','时','泰','盛','雄','琛','钧','冠','策','腾','楠','榕','风','航','弘','秀','娟','英','华','慧',
            '巧','美','娜','静','淑','惠','珠','翠','雅','芝','玉','萍','红','娥','玲','芬','芳','燕','彩','春',
            '菊','兰','凤','洁','梅','琳','素','云','莲','真','环','雪','荣','爱','妹','霞','香','月','莺','媛',
            '艳','瑞','凡','佳','嘉','琼','勤','珍','贞','莉','桂','娣','叶','璧','璐','娅','琦','晶','妍','茜',
            '秋','珊','莎','锦','黛','青','倩','婷','姣','婉','娴','瑾','颖','露','瑶','怡','婵','雁','蓓','纨',
            '仪','荷','丹','蓉','眉','君','琴','蕊','薇','菁','梦','岚','苑','婕','馨','瑗','琰','韵','融','园',
            '艺','咏','卿','聪','澜','纯','毓','悦','昭','冰','爽','琬','茗','羽','希','欣','飘','育','滢','馥',
            '筠','柔','竹','霭','凝','晓','欢','霄','枫','芸','菲','寒','伊','亚','宜','可','姬','舒','影','荔',
            '枝','丽','阳','妮','宝','贝','初','程','梵','罡','恒','鸿','桦','骅','剑','娇','纪','宽','苛','灵',
            '玛','媚','琪','晴','容','睿','烁','堂','唯','威','韦','雯','苇','萱','阅','彦','宇','雨','洋','忠',
            '宗','曼','紫','逸','贤','蝶','菡','绿','蓝','儿','翠','烟','组','祖');
        $first_num = array_rand($first_name);
        $last_result1 = array_rand($last_name);
        $last_num2 = array_rand($last_name,2);
        $last_result = $last_name[$last_num2[0]].$last_name[$last_num2[1]];
        return rand(0,1) ? $first_name[$first_num].$last_name[$last_result1] : $first_name[$first_num].$last_result;
    }
}